<!--
  @Description: 拖拽排序
  @Author: Mr.Li
  @E-mail: 
  @Date: 5/6/2025 15:17
-->
<template>
  <!--  sortable  -->
  <div class="conversation-list" ref="conversationRef">
    <div class="conversation-item draggable" v-for="item in list" :key="item.id">
      <div class="avatar">
        <img :src="item.avatar" alt="" />
      </div>
      <div class="info-wrapper">
        <div class="name-wrapper">
          <div class="name">{{ item.name }}</div>
          <div class="time">{{ item.time }}</div>
        </div>
        <div class="content">{{ item.lastMessage }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Avatar1 from './avatar-1.jpg';
import Avatar2 from './avatar-2.jpg';
import Avatar3 from './avatar-3.jpg';
import Avatar4 from './avatar-4.jpg';
import Sortable from 'sortablejs';

const list = ref([
  {
    id: 1,
    name: '番茄酱',
    avatar: Avatar1,
    time: '05/04 08:00',
    lastMessage: '早上好',
  },
  {
    id: 2,
    name: '坤坤',
    avatar: Avatar2,
    time: '05/06 09:00',
    lastMessage: '你好吗？',
  },
  {
    id: 3,
    name: '小橘子',
    avatar: Avatar3,
    time: '05/01 21:00',
    lastMessage: '我在拿快递',
  },
  {
    id: 4,
    name: '荔枝',
    avatar: Avatar4,
    time: '05/01 08:00',
    lastMessage: '有事吗？',
  },
  {
    id: 5,
    name: '苹果',
    avatar: Avatar1,
    time: '05/01 08:00',
    lastMessage: '？',
  },

  {
    id: 6,
    name: '树莓派',
    avatar: Avatar3,
    time: '05/03 20:00',
    lastMessage: '？？',
  },
]);
const conversationRef = ref();
onMounted(() => {
  initSortable();
});

function initSortable() {
  new Sortable(conversationRef.value, {
    animation: 150,
    dragClass: 'sortable-drag',
    filter: '.ignore-sort',
    draggable: '.draggable',
    // 结束拖拽
    onEnd(evt) {
      let oldIndex = evt.oldIndex;
      let newIndex = evt.newIndex;
      if (oldIndex === newIndex) {
        return;
      }
      // 删除原来的位置
      const oldItem = list.value.splice(oldIndex, 1)[0];
      // 插入到新的位置
      list.value.splice(newIndex, 0, oldItem);
    },
  });
}
</script>

<style scoped lang="scss">
.conversation-list {
  width: 400px;
  background: #efefef;

  &.sortable-drag {
    background: red !important;
  }
}

.conversation-item {
  display: flex;
  justify-content: flex-start;
  align-content: center;
  gap: 10px;
  padding: 15px;

  &:hover {
    background: #cecece;
  }

  .avatar {
    font-size: 0;

    img {
      width: 40px;
      height: 40px;
    }
  }

  .info-wrapper {
    flex: 1;

    .name-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        font-size: 15px;
      }

      .time {
        font-size: 13px;
        color: #666;
      }
    }

    .content {
      font-size: 12px;
      color: #777;
      width: 220px;
      margin-top: 3px;
    }
  }
}
</style>
